package com.cy.sys.service.Impl;

import com.cy.sys.mapper.BillMapper;
import com.cy.sys.mapper.GoodsMapper;
import com.cy.sys.pojo.Bill;
import com.cy.sys.pojo.Goods;
import com.cy.sys.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private BillMapper billMapper;

    @Override
    public int saveGoods(Goods entity) {
        return goodsMapper.insertGoods(entity);
    }

    @Override
    public int updateGoods(Goods entity) {
        return goodsMapper.updateGoods(entity);
    }

    @Override
    public Goods findById(Integer id) {
        return goodsMapper.selectById(id);
    }

    @Override
    public List<Goods> findGoods(Goods entity) {
        return goodsMapper.selectGoods(entity);
    }

    @Override
    public int deleteGoodsById(Integer... id) {
        return goodsMapper.deleteGoodsById(id);
    }

    /**
     * 商品销售功能
     * @param goodsId
     * @param saleQuantity
     */
    @Override
    @Transactional
    public void doSale(Integer goodsId, Integer saleQuantity) {
    //1.库存对应减少
        Goods goods = goodsMapper.selectById(goodsId);
        goods.setStock(goods.getStock()-saleQuantity);
        goodsMapper.updateGoods(goods);
        //2.添加账单
        Bill bill = new Bill();
        bill.setGoodsId(goodsId);
        bill.setQuantity(saleQuantity);
        bill.setAmount(goods.getPrice()*saleQuantity);
        billMapper.insertBill(bill);
    }
}
